package com.paso.security.springmvc.service.impl;

import com.paso.security.springmvc.model.AuthenticationRequest;
import com.paso.security.springmvc.model.UserDto;
import com.paso.security.springmvc.service.AuthenticationService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * 用户认证
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {
    @Override
    public UserDto authentication(AuthenticationRequest authenticationRequest) {
        // 校验用户的身份信息是否合法

        // 校验参数是否为空
        if (authenticationRequest == null || StringUtils.isEmpty(authenticationRequest.getUsername()) || StringUtils.isEmpty(authenticationRequest.getPassword())) {
            throw new RuntimeException("账号或密码为空");
        }

        // 根据账号去查询数据库
        UserDto user = getUserDto(authenticationRequest.getUsername());

        // 判断数据库查询出来的用户是否为空
        if (user == null) {
            throw new RuntimeException("查询不到该用户");
        }

        // 校验密码
        if (!user.getPassword().equals(authenticationRequest.getPassword())) {
            throw new RuntimeException("账号或密码错误");
        }

        // 认证通过，返回用户的身份信息
        return user;
    }


    // 根据账号查询用户信息
    private UserDto getUserDto(String username){
        return  userDtoMap.get(username);
    }

    // 用户信息
    private Map<String, UserDto> userDtoMap = new HashMap<>();
    {
        HashSet<String> authorities1 = new HashSet<>();
        authorities1.add("p1"); // 我们人为的把p1和r/r1绑定
        HashSet<String> authorities2 = new HashSet<>();
        authorities2.add("p2"); // 我们人为的把p2和r/r2绑定

        userDtoMap.put("zhangsan",new UserDto("1010","zhangsan","123","张三","13342",authorities1));
        userDtoMap.put("lisi",new UserDto("1011","lisi","456","李四","133266",authorities2));
    }


}
